package com.example.teamtribe.hello;

import android.os.Bundle;
import android.util.Log;

import com.example.teamtribe.common.Back;
import com.example.teamtribe.common.CallbackStore;
import com.example.teamtribe.utils.HttpUtil;
import com.example.teamtribe.utils.ParseMD5;
import com.example.teamtribe.utils.URLStore;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class HelloModel {

    public void sendCode(String phone, final Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("phone", phone);
        HttpUtil.post(URLStore.USER_SMS_SEND, params, CallbackStore.getCallback(back));
    }

    public void register(final String username, String psw,final String phone, String code, final Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("username", username);
        params.put("password", ParseMD5.parseStrToMd5U16(psw));
        params.put("phone", phone);
        params.put("validateCode", code);
        HttpUtil.post(URLStore.USER_REGISTER, params, CallbackStore.getCallback(back));
    }

    public void login(final String username, String psw, final Back back) {
        final String type = username.contains("@") ? "1" : "2";
        Map<String, String> params = new HashMap<>();
        params.put("username", username);
        params.put("password", ParseMD5.parseStrToMd5U16(psw));
        params.put("usernameType", type);
        HttpUtil.post(URLStore.USER_LOGIN, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                back.failure(HttpUtil.getFailureMeg());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject object = new JSONObject(response.body().string());
                    Log.d("login", object.toString());
                    final int status = object.getInt("code");
                    if (status != 0) {
                        back.failure(HttpUtil.getCodeMeg(status));
                    } else {
                        Bundle bundle = new Bundle();
                        bundle.putString("TeamTribeToken", object.getString("TeamTribeToken"));
                        bundle.putInt("id", object.getInt("id"));
                        back.success(bundle);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
